<%@page import="java.util.List"%>
<%@page import="org.proddevplm.dao.data.User"%>
<%@page import="org.proddevplm.constants.UserConstants"%>

<script>	
	<%
	User loggedUser = (User) session.getAttribute(UserConstants.USER);
	List<User> users = (List) session.getAttribute("usersOnProject");
	%>
	var roomName = "default";
	var smile="<img src='http://images2.wikia.nocookie.net/__cb20071012163228/callofduty/images/d/df/Smiley.gif'>";
	var lastMessageIndex = 0;
	var userId = <%=loggedUser.getId()%>;
	var loggedUserName="<%=loggedUser.getSurname() + " " + loggedUser.getName()%>";
	var lastMessage = "";
	var objDiv = document.getElementById("chatwindow");
	
	$(function(){
		$("input:button").button();
		$("#uploadButtons").buttonset();
		$("#upload").hide();
	});
	
	function showUpload(){
		$("#upload").show();
	}
	
	function hideUpload(){
		$("#upload").hide();
	}
	
	$("#message").keyup(
		function(event) {
			if (event.keyCode == 13) {
				var message = adaptMessage($("#chatmessage").val());
				lastMessage=$("#chatmessage").val();
				//$("#chatwindow").append(message);							
				$("#chatmessage").val("");
				persist(escape(message));
				
				} 
			else if (event.keyCode == 38) {
				$("#chatmessage").val(lastMessage);
			}
		});

	function adaptMessage(message) {
		if (isVrml(message))
		{
			return message;				
		}
		if (isUrl(message)) {			
			
			if (isImage(message)) {
				return "</br><b>" + loggedUserName + ":&nbsp;</b></br><img src='"+message+"'>";
			} else {
				return "</br><b>" + loggedUserName + ":&nbsp;</b><a href='" + message +"'>"+message+"</a>";
			}
		}
		
		message = message.replace(/:\)/g,smile);
				
		return "</br><b>" + loggedUserName + ":&nbsp;</b>" + message;
	}
	
	function isUrl(s) {
		var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
		return regexp.test(s);
	}

	function isImage(s) {
		var regexp = new RegExp(".*(jpg|png|gif)$");
		return regexp.test(s);			
	}
	
	function isVrml(s) {
		var regexp = new RegExp(".*(vrml|wrl)$");
		return regexp.test(s);			
	}

	
	function persist(message) {
		var arguments;
		if (roomName == null)
			arguments = "userMessage="+message;
		else
			arguments = "userMessage="+message+"&roomName="+roomName;
		ajaxCall("openRoomManager", "0", arguments, null);
	}
	
	
	
	function selectRoom(selectedRoomName) {
		lastMessageIndex = 0;
		objDiv.innerHTML ="";
		roomName=selectedRoomName;
		pollData();
	}
	
	var lastData;
	
	function onMessagesReceived(data) {
	
		if(data == "")
			return;		
		var jsonData = $.evalJSON(data);
		
		lastData = jsonData;
		
		for (var i in jsonData.messages)
			{
				var messageValue = jsonData.messages[i].value;
				if (isVrml(messageValue))
					{
						$("#chatwindow").append("<p onclick='loadVrml(\""+messageValue+"\")>Click to open shared 3D Object ("+messageValue+")</p>");
					} 
				else
					{
						$("#chatwindow").append(messageValue);
					}
			
		}
		lastMessageIndex =  jsonData.lastindex;
		objDiv.scrollTop = objDiv.scrollHeight;
	}
	
	function pollData()
	{
		if (roomName == null)
			ajaxCall("openRoomManager", "1", "getFromIndex="+lastMessageIndex, onMessagesReceived)
		else
			ajaxCall("openRoomManager", "1", "roomName="+roomName+"&getFromIndex="+lastMessageIndex, onMessagesReceived)
	}
	
	
	function closeVrml()
	{
		$("#demoElement").empty();
		$("#actualChatWindow").width("99%")
		$("#demoElement").width("1%");
	}
	
	function loadVrml(vrmlLocation)
	{		
		$("#actualChatWindow").width("50%")
		$("#demoElement").width("50%");
		$("#demoElement").innerHtml = "";
		$("#demoElement").append('<p onclick="closeVrml()">[close]<p><EMBED SRC="'+vrmlLocation+'" WIDTH="100%" HEIGHT="90%">');
	}
	
	function addRoom()
	{
		roomName = $("#roomName").val();
		var content="<p style=\"text-weight:bold;\" onclick=\"selectRoom('"+roomName+"')\">"+roomName+"</p>";
		$("#rooms").append(content);
		selectRoom(roomName);
	}
	
	
	function getRoomNames(){
		ajaxCall("openRoomManager", "2", null, populateRoomNames);
	}
	
	function populateRoomNames(roomNames){
		
		roomNames = roomNames.substring(0, roomNames.length-2);
		var roomNamesArray = roomNames.split("~");
		$("#rooms").empty();
		var content="";
		content="<p style=\"text-weight:bold;\" onclick=\"selectRoom('default')\">default</p>";
		$("#rooms").append(content);
		for (var i=0; i<roomNamesArray.length; i++){
	alert('-'+roomNamesArray[i]+'-');			
			content="<p style=\"text-weight:bold;\" onclick=\"selectRoom('"+roomNamesArray[i]+"')\">"+roomNamesArray[i]+"</p>";
			$("#rooms").append(content);
		}
		
	}
	
	pollData();
	getRoomNames();
	
	var pollChatData = window.setInterval("pollData()", 2000);
</script>


<div class="containerSmall" id="leftwin" style="width: 15%; height: 80%; float: left; overflow: auto;">
	<div style="margin-top:1%;">
		<b>Users on project</b>
		<hr/>
		<%
		for (User user : users) {
			out.println("<b>" + user.getSurname() + " " + user.getName()+ "</b></br>");
		}
		%>
	</div>
	<div style="padding-top:30px;">
		<b>Rooms on project</b>
		<hr/>
		<div id="rooms">
			
		</div>
		<div style="padding-top:20px">
		
		
		<b>Add room</b>
		<div style="width:100%; margin-top:5px">
			<input class="regInput" id="roomName" type="text" style="width:75%; float:left">
			<input type="button"  value="+" onclick="addRoom()" style="margin-left:2%; width:22%; height:28px; float:left"/>
			<div style="clear:both"></div>
		</div>
		</div>
	</div>
	
</div>
<div class="containerSmall" id="rightwin" style="width: 80%; height: 80%; margin-left:1%; margin-right:auto; border: 1px solid #FF00FF; float: left;">
	<div id="actualChatWindow" style="width:99%; height:80%;float:left">
		<div style="margin-top:1%;">
			<b>Current messages in this room:</b>
		</div>
		<div class="containerBig" id="chatwindow" style="width: 100%;  height:80%; margin-top:0.5%; overflow: auto;">
		</div>
		<div style="clear:both"></div>
	</div>
	<div id="demoElement" style="width:1%; height:80%;float:left">
	</div>
	<div style="clear:both:"></div>
	<div id="message" style="width: 100%; height:20%;">
		<div style="margin-top:1%; color:#555555">
			<b>Insert text here</b>
		</div>
		<input class="regInput" id="chatmessage" type="text" style="width: 100%; margin-top:0.5%; "/>
		<div style="width:100%; margin-top:10px;">
			<div id="uploadButtons" style="width:25%; float:left">
				<input type="radio" name="radio" id="showUpload" onclick="showUpload()"/><label for="showUpload"><b>Share 3D file</b></label>
				<input type="radio" name="radio" id="hideUpload" onclick="hideUpload()"/><label for="hideUpload"><b>Hide upload</b></label>
			</div>
			
			<div id="upload" style="width:70%; float:left">			
				<script>
					function uploadFileFunction() {
						
						var fileNameValue = $("#fileName").val();
						var message = "/proddev/CommonsFileUploadServlet?fileName="+fileNameValue;
						$("#chatmessage").val("");
						alert(message);
						persist(escape(message));
						$("#uploadFile").submit();
					}
				</script>
				<form name="uploadFile" id="uploadFile" action="/proddev/CommonsFileUploadServlet" enctype="multipart/form-data" method="post" style="margin:0">
					<input id="fileName" type="file" name="fileName" />
					<a href="#" onClick="uploadFileFunction()">Upload file</a>
				</form>
			</div>
			
			<div style="clear:both"></div>
		</div>
	</div>
	
	<div style="clear:both"></div>
</div>




